package com.reggie.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.reggie.constant.MessageConstant;
import com.reggie.dto.UserLoginDTO;
import com.reggie.entity.User;
import com.reggie.exception.LoginFailedException;

import com.reggie.mapper.UserMapper;
import com.reggie.service.UserService;
import com.reggie.utils.HttpClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.HashMap;

@Service
public class UserServiceImpl implements UserService {

    public static final String LOGIN_URL = "https://api.weixin.qq.com/sns/jscode2session";


    @Autowired
    private UserMapper userMapper;

    @Value("${reggie.wechat.appid}")
    private String appid;
    @Value("${reggie.wechat.secret}")
    private String secret;

    //获取用户iD
    private String getOpenid(String code){
        //调用微信接口服务,根据授权码 获取微信用户的openId
        HashMap<String, String> param = new HashMap<>();
        param.put("appid",appid); //开发者的小程序id
        param.put("secret",secret); //开发者小程序的授权码
        param.put("js_code",code);
        param.put("grant_type","authorization_code");

        //数据格式：{openid:xxxx,session_key:xxxx}
        String res = HttpClientUtil.doGet(LOGIN_URL, param);
        JSONObject jsonObject = JSON.parseObject(res);
        String openid = jsonObject.getString("openid");
        return openid;
    }

   //微信用户登录
    public User wxLogin(UserLoginDTO userLoginDTO) {
        //授权码
        String code = userLoginDTO.getCode();
        //获取微信用户的openId
        String openid = getOpenid(code);

        if(openid==null){
            //如果没有获取到用户Id
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }

        //根据openid查询用户
        User user = userMapper.getByOpenid(openid);
        if(user==null){
            //如果数据不 不存在这个用户 就自动注册
             user = new User();
             user.setOpenid(openid);
             user.setCreateTime(LocalDate.now());
             userMapper.insert(user);
        }
        return user;
    }
}
